package org.ting.book.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.ting.book.constants.Constants;
import org.ting.book.utils.JwtUtils;

/**
 * 定义拦截器检查用户token是否有效
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        log.info("接收到token：{}", token);
        //校验token
        if(token == null) {
            response.setStatus(401);
            return false;
        }
        if(JwtUtils.parseToken(token) == null) {
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
